define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'editable','template'], function ($, undefined, Backend, Table, Form, undefined,Template) {
    var Controller = {
        index: function () {
            Table.api.init();
            this.table.first();
            this.table.second();
            $(document).on('change','.unit-id',function () {
                $("input[data-name=unit_id]").val($(this).val());
            });
        },table: {
            first: function (){
                //====== 选择分类
                $(document).on('change','.dry-select',function () {
                    $('input[name=category_id]').val($(this).val());
                });
                // 表格1
                var table1 = $("#table1");
                table1.bootstrapTable({
                    url: 'yexam/question_error/subject',
                    toolbar: '#toolbar1',
                    sortName: 'id',
                    search: true, //====== 是否启用快搜索框
                    searchFormVisible : true,
                    commonSearch : true,
                    order:'asc',
                    showToggle: false, //===== 是否显示切换,
                    showExport: false,
                    pk: 'id',
                    showColumns: false,
                    pageSize: 20,
                    pageList : [20,40,60,80],
                    columns: [
                        [
                            {field: 'short_name',align:"left" ,title: __('科目名称'),operate: false, formatter: function ($data,$all) {
                                    return $data+`<span class='badge bg-info' style="display: inline-block;margin-left: 4px;">${$all.total}</span>`+`<span class="badge bg-red">${$all.free}</span>`;
                                }},
                            //=======================================================公共搜索的样式 ========
                            {field: 'category_id',title: __(''),visible: false,searchList: function () {return Template("tpl",{});}},
                            {field: 'id',visible: false}
                        ]
                    ],
                    //=============== 单击行 ===============
                    onClickRow: (row, $element) =>{
                        $($element).addClass('active-select').siblings().removeClass('active-select');
                        window.subjectId = row.id;
                        $("#myTabContent2 .form-commonsearch input[name='short_name']").val(row.id);
                        $("#myTabContent2 .btn-refresh").trigger("click");
                        let subject = $('#myTabContent2 .subjectId');
                        subject.attr('href',subject.attr('data-link')+row.id);
                        //================= 更改联动搜索 ============
                        $.get('yexam/unit/cxselect?subject_id='+window.subjectId,function (response) {
                            let str = ["<option value=''>请选择</option>>"];
                            for (const strElement of response.data) {
                                str.push(`<option value="${strElement.value}">${strElement.name}</option>`);
                            }
                            $('.january').removeAttr('disabled').html(str.join(""));
                        });
                        //============== 更改联动搜索--题型 ==========
                        $.get('yexam/examination/getQuestionType?id='+window.subjectId,function (response) {
                            let str = ["<option value=''>请选择</option>"];
                            for (const strKey of response) {
                                str.push(`<option value='${strKey.value}'>${strKey.name}</option>`);
                            }
                            $("select[name=questiontype]").html(str.join(""));
                        });
                    },
                    //=================== 更改查询参数 支持无限级分类联动  ===============
                    queryParams: function (params) {
                        let categoryId = $('input[name=category_id]').val();
                        if (categoryId != '')
                        {
                            let filter = JSON.parse(params.filter);
                            let op = JSON.parse(params.op);
                            filter.category_id = categoryId;
                            op.category_id = $('input[data-name="category_id"]').val();
                        }
                        return params;
                    }
                });
                // 为表格1绑定事件
                Table.api.bindevent(table1);
            },
            second: function () {
                var table = $("#table2");
                // 初始化表格
                table.bootstrapTable({
                    url: 'yexam/examination/index',
                    escape: false,
                    pk: 'id',
                    sortName: 'id',
                    toolbar : "#toolbar2",
                    sortOrder:'asc',
                    order:'asc',
                    search: false,
                    extend: {
                        index_url: 'yexam/examination/index' + location.search,
                        edit_url: 'yexam/question/edit',
                        del_url: 'yexam/question/del',
                        question_error_url: "yexam/examination/questionError",
                        multi_url : "yexam/question/multi"
                    },
                    pageList : [20,40,60,80],
                    commonSearch: true,
                    columns: [
                        [
                            {checkbox: true},
                            {field: 'id', title: __('Id')},
                            {field: 'question_name', title: __('题目名称'),"class" : "init",operate : "LIKE",align: 'left',width:'220px',},
                            {field: 'questiontype', title: __('题目类型'), searchList: [], formatter: Table.api.formatter.normal},
                            {field: 'right_answer', title: __('正确答案'),formatter: Controller.api.formatter.right_answer,operate: false},
                            {field: 'area', title: __('解析'), style:"display:block;", //============= 用于高级搜索 =============
                                "class" : 'init',visible: false, operate: false
                            },
                            {field:'questiontime',title: __("录入时间"),operate: 'RANGE',addClass: "datetimerange",formatter: Table.api.formatter.datetime},
                            {field: 'unit_id',title: __("章节"),searchList: function () {return Template("unit_tpl",{});}},
                            {field:'questionselect',title: __("选项"),"class" : 'init',visible : true,operate: false},
                            {field:'questionlevel',title: __("难度"),searchList : {3 : '难', 2 : '中', 1 : '易'}},
                            {field: "is_free",title: __("付费"),operate: false,formatter: Table.api.formatter.toggle},
                            {field:'questionauthor',title: __("录入人"),operate: false},
                            {field:'alterpeople',title: __("修改人"),operate: false},
                            {field:'altertime',title: __("修改时间"),operate: false},
                            {field:'alternum',title: __("修改次数"),operate: false},
                            {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate,}
                        ]
                    ],
                    //============ 查询参数
                    queryParams: function (params) {
                        let filter = JSON.parse(params.filter);
                        let op = JSON.parse(params.op);
                        filter.subject_id = window.subjectId;
                        op.subject_id = '=';
                        let unitId = $("input[data-name=unit_id]").val();
                        if (unitId !== '=')
                        {
                            filter.unit_id = unitId;
                            op.unit_id = '=';
                        }
                        params.filter = JSON.stringify(filter);
                        params.op = JSON.stringify(op);
                        return params;
                    }
                });
                // 为表格绑定事件
                Table.api.bindevent(table);
            },
        },
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        recyclebin: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    'dragsort_url': ''
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: 'yexam/examination/recyclebin' + location.search,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'question_name', title: __('题目名称'), align: 'left'},
                        {
                            field: 'deletetime',
                            title: __('Deletetime'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'operate',
                            width: '130px',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'Restore',
                                    text: __('Restore'),
                                    classname: 'btn btn-xs btn-info btn-ajax btn-restoreit',
                                    icon: 'fa fa-rotate-left',
                                    url: 'yexam/examination/restore',
                                    refresh: true
                                },
                                {
                                    name: 'Destroy',
                                    text: __('Destroy'),
                                    classname: 'btn btn-xs btn-danger btn-ajax btn-destroyit',
                                    icon: 'fa fa-times',
                                    url: 'yexam/examination/destroy',
                                    refresh: true
                                }
                            ],
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        api: {
            formatter:{
            },
            bindevent: function () {
                $("#c-package_ids").data("params", function (obj) {
                    return {custom: {category_id: $("#c-category_id").val()}};
                });
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});
